package com.my.socket.nio.v26;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by ZhongGang
 * at 2018/8/20 17:15
 */
public class Reactor implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Reactor.class);

    private ServerSocketChannel serverSocketChannel;
    private Selector selector;

    public Reactor(String hostname, int port) throws Exception {
        if (port <= 0) {
            throw new IllegalArgumentException();
        }

        this.selector = Selector.open();

        this.serverSocketChannel = ServerSocketChannel.open();
        this.serverSocketChannel.bind(new InetSocketAddress(hostname, port));
        this.serverSocketChannel.configureBlocking(false);
        this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT, new Acceptor(this.selector, this.serverSocketChannel));
    }

    @Override
    public void run() {
        while (!Thread.interrupted()) {
            try {
                this.selector.select();
                Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    //dispatch
                    SelectionKey next = iterator.next();
                    iterator.remove();

                    Runnable runnable = (Runnable) next.attachment();
                    if (runnable != null) {
                        LOGGER.info("attachment: {}", runnable);
                        runnable.run();
                    }
                }
            } catch (Exception e) {
                LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Reactor reactor = new Reactor("127.0.0.1", 9999);
        new Thread(reactor).start();
    }
}
